//引入axios
import axios from "axios"
//loading加载
import { ElLoading } from 'element-plus'
import { ElMessage } from 'element-plus'
// 引入store
import store from "../store/index.js";
// //使用create创建axios实例
let loadingObj = null
const Service = axios.create({

    //同个服务器发布时的baseURL http://43.142.131.251:8080/
    //前后端分离发布时的baseURL
    timeout: 40000,
    baseURL: "http://localhost:8081",
    headers:{
    "Content-type": "application/json;charset=utf-8",
    // 这里的token为每次请求时携带的
    token: store.state.userInfo.token

    },
})

//请求拦截-增加loading，，对请求做统一处理
Service.interceptors.request.use(config => {
    // 默认headers.token数据格式为json格式
    config.headers.token= JSON.parse(localStorage.getItem('token'));
    config.headers.ContentType="application/json;charset=utf-8";
    // console.log('token-->'+localStorage.getItem('token'));
    //添加加载动画
    loadingObj = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    return config
})
//响应拦截-对返回值做统一处理
Service.interceptors.response.use(response => {

    const data = response.data
    if (data.status === 202) {
        ElMessage.error(data.msg || "失败")
        loadingObj.close()
    } else if (data.status === 201) {
        // ElMessage.success("success")
        loadingObj.close()
    } else if (data.status === 200) {
        loadingObj.close()
    }
    return response.data
});


//post 请求
export const post = config => {
    return Service({
        ...config,
        methods: "post",
        data: config.data
    })
}
//get 请求
export const get = config => {
    return Service({
        ...config,
        methods: "get",
        params: config.data
    })
}
// put请求
export const put = config => {
    return Service({
        ...config,
        method: "put",
        data: config.data
    })
}

//删除请求
export const del = config => {
    return Service({
        ...config,
        method: "put",

    })
}